package com.simple.util.api.aliyun;

import com.simple.util.security.Md5Util;

/**
 * @program: simple_tools
 * @description: 阿里云工具类
 * @author: Mr.chen
 * @create: 2020-06-08 15:58
 **/
public class AliyunLiveUtil {
    /**
     * 获取地址
     * AppName与 StreamName参数支持英文、数字、“-”、“_”符号，长度限制在255字符以内。
     * @param pushDomain 推流域名
     * @param watchDomain 观看域名
     * @param appName 应用名
     * @param streamName 流名称，必须唯一
     * @param min 分钟
     * @return
     */
    public static AliyunLiveAddress generateLiveAddress(String pushDomain, String watchDomain, String privateKey, String live_privateKey, String appName, String streamName, Long min){
        String timestamp = String.valueOf((System.currentTimeMillis()/1000) + (min * 60));//秒
        String rand = "0";
        String uid = "0";
        String uri = "/"+appName +"/" + streamName ;
        String params = timestamp + "-" + rand + "-" + uid ;

        //rstring = "URI-Timestamp-rand-uid-PrivateKey"
        String rstring = uri + "-" + params + "-" + privateKey;
        //边缘推流地址
        String url = "rtmp://" + pushDomain + uri +"?auth_key=" + params + "-"+ Md5Util.encode(rstring).toLowerCase();

        String rtmpStr = uri+ "-" + params + "-" + live_privateKey;
        String rtmp = "rtmp://" + watchDomain + uri + "?auth_key=" + params + "-" + Md5Util.encode(rtmpStr).toLowerCase();

        String fstring = uri + ".flv" + "-" + params + "-" + live_privateKey;
        String flv = "https://" + watchDomain  + uri + ".flv" + "?auth_key=" + params + "-" + Md5Util.encode(fstring).toLowerCase();

        String mstring = uri + ".m3u8" + "-" + params + "-" + live_privateKey;
        String m3u8 = "http://" + watchDomain + uri + ".m3u8" + "?auth_key=" + params + "-" + Md5Util.encode(mstring).toLowerCase();

        AliyunLiveAddress obj = new AliyunLiveAddress();
        obj.setUrl(url);
        obj.setRtmp(rtmp);
        obj.setFlv(flv);
        obj.setM3u8(m3u8);
        return obj;
    }

    /**
     * @param appName 应用名
     * @param streamName 流名称，必须唯一
     * @return
     */
    public static AliyunLiveAddress generateLiveAddress(String pushDomain, String watchDomain, String privateKey, String live_privateKey, String appName, String streamName){
        return generateLiveAddress(pushDomain, watchDomain, privateKey, live_privateKey, appName, streamName, 120L);
    }
}
